package com.mvc.business.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.base.service.BaseCompanyManager;
import com.mvc.base.service.CustomerManager;
import com.mvc.business.model.OrderAssociated;
import com.mvc.business.model.Packing;
import com.mvc.framework.dao.HibernateIdUtils;
import com.mvc.framework.model.Auditable;

@Service
public class PackingManager extends BaseCompanyManager<Packing, Integer> {
	@Autowired
	private PackingItemManager	   packingItemManager;

	@Autowired
	private OrderManager	       orderManager;

	@Autowired
	private CustomerManager	       customerManager;

	@Autowired
	private OrderAssociatedManager	orderAssociatedManager;

	public Packing getObject(Integer packingId) {
		Packing packing = getByObjectId(packingId);
		packing.setCustomer(customerManager.getByObjectId(packing.getCustomerId()));
		packing.setCompany(companyManager.getByObjectId(packing.getCompanyId()));
		packing.setPackingItems(packingItemManager.getPackingItemsByPackingId(packing.getObjectId()));
		return packing;
	}

	public void save(Packing entity) {
		packingItemManager.summaryPackingItemSummary(entity);
		if (null == entity.getId()) {
			entity.setCompanyId(customerManager.getByObjectId(entity.getCustomerId()).getCompanyId());
			entity.setStatus(Packing.STATUS_CREATED);
			entity.setPackingDate(new Date());
			Integer oldOrderId = entity.getObjectId();
			entity.setObjectId(HibernateIdUtils.getUnCacheCustomizeId(getHibernateTemplate().getSessionFactory(), "packingId"));
			packingItemManager.updatePackingId(oldOrderId, entity.getObjectId());
			orderAssociatedManager.updateAssociated(oldOrderId, entity.getObjectId(), OrderAssociated.TYPE_PACKING);
		}
		super.save(entity);
	}

	public List<Packing> getPackingsByCommercialInvoiceId(Integer commercialInvoiceId) {
		String sql = "select A from " + Packing.class.getName() + " A where A.commercialInvoiceId=? AND A.recStatus=? ";
		return searchBySql(sql, new Object[] { commercialInvoiceId, Auditable.REC_STATUS_VALID });
	}

}
